package me.aristotll.converter;

import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

import java.io.File;

/**
 * Name: TrueJavaToGroovyAction<br>
 * User: Yao<br>
 * Date: 17/6/24<br>
 * Time: 11:05<br>
 */
public class TrueJavaToGroovyAction extends AnAction {
    @SuppressWarnings("WeakerAccess")
    @NotNull
    public static final String BACKUP_EXTENSION = JavaFileType.DOT_DEFAULT_EXTENSION + "_bak";

    @NotNull
    private static final Logger logger = Logger.getInstance(TrueJavaToGroovyAction.class);

    @Override
    public void update(AnActionEvent e) {
        super.update(e);
        VirtualFile f = e.getData(PlatformDataKeys.VIRTUAL_FILE);
        e.getPresentation().setEnabledAndVisible(f != null && f.getFileType().equals(JavaFileType.INSTANCE));
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        if (project == null) {
            return;
        }
        final VirtualFile f = e.getData(PlatformDataKeys.VIRTUAL_FILE);
        if (f != null && f.getFileType().equals(JavaFileType.INSTANCE)) {
/*
            Module module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(f);
            if (module == null) {
                return;
            }
            ModuleRootManager mrm = ModuleRootManager.getInstance(module);
            VirtualFile[] sources = mrm.getSourceRoots();

            for (VirtualFile source : sources) {
                if (source.getName().equals("groovy")) {
                }
            }
*/

            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                public void run() {
                    try {
                        final String path = f.getPath();
                        /*
                        this nameWithoutExtension just have the file name like `Test`
                         */
                        final String nameWithoutExtension = f.getNameWithoutExtension();
                        final String parentDir = f.getParent().getPath();
                        final String newGroovyFile = parentDir + File.separator + nameWithoutExtension + ".groovy";
                        Java2Groovy.newConvertedFile(path, newGroovyFile);
                        f.rename(this, nameWithoutExtension + BACKUP_EXTENSION);
                    } catch (Exception exception) {
                        logger.warn("conversion error", exception);
//                        exception.printStackTrace();
                    }

                }
            });
        }
    }
}
